using System;
using System.Web;
using System.Threading;
using System.Data;

namespace ECCIT.Data
{
	/// <summary>
	/// 
	/// </summary>
	public class DataCacheListener : IHttpModule
	{
		static Timer timer;
		int interval = 5000;

		public String ModuleName 
		{ 
			get { return "DataCacheListener"; } 
		}    

		public void Init(HttpApplication application) 
		{ 
			// Wire-up application events
			if (timer == null)
				timer = new Timer(new TimerCallback(ScheduledWorkCallback), application.Context, interval, interval);
		}

		public void Dispose() 
		{
			timer = null;
		}

		private void ScheduledWorkCallback(object sender) 
		{
			HttpContext context = (HttpContext) sender;
			Listen(context);			
		}

		private void Listen(HttpContext context) 
		{
			string cmdSelect = "SELECT * FROM CHANGENOTIFICATION";
			
			using(IDataReader reader = DBHelper.ExecuteReader(cmdSelect))
			{
				while (reader.Read()) 
				{
					string tableNameList = reader["TableName"].ToString().Trim();
					string[] tableNameArray = tableNameList.Split(char.Parse(","));
					
					string cacheKey = DataCache.GetDependencyKey(tableNameArray);
					if( context.Cache[cacheKey] != null )
					{
						int changeID = int.Parse( context.Cache[cacheKey].ToString() );

						if (changeID != int.Parse( reader["ChangeID"].ToString() ))
							context.Cache.Remove(cacheKey);	
					}
				}
                reader.Close();
			}
		}
	}
}
